import { Inject, Injectable } from "@nestjs/common";
import { Cache, CACHE_MANAGER } from "@nestjs/cache-manager";
import { PrismaService } from "@app/prisma";
import { User } from "@prisma/client";

@Injectable()
export class UserService {
  constructor(
    private prisma: PrismaService,
    @Inject(CACHE_MANAGER)
    private cacheManager: Cache,
  ) {}

  async findOne(username: string, password: string): Promise<User | undefined> {
    return this.prisma.user.findUnique({
      where: {
        username,
        password,
      },
    });
  }

  async getPermissionByUserId(userId: number): Promise<any[] | undefined> {
    const permissionCacheKey = `permission-${userId}`;
    const cachedPermission: any =
      await this.cacheManager.get(permissionCacheKey);
    if (cachedPermission) {
      console.log("cached");
      return cachedPermission;
    }
    try {
      const userWithRolesWithPermissions = await this.prisma.user.findUnique({
        where: { id: userId },
        include: {
          roles: {
            include: {
              role: {
                include: {
                  permissions: {
                    include: {
                      permission: true,
                    },
                  },
                },
              },
            },
          },
        },
      });
      let totalPermissions = [];
      userWithRolesWithPermissions.roles.map((role) => {
        role.role.permissions.map((permissions) => {
          totalPermissions = [...totalPermissions, permissions.permission.name];
        });
      });
      await this.cacheManager.set(permissionCacheKey, totalPermissions);
      return totalPermissions;
    } catch (err) {
      console.log(err);
    }
  }
}
